import { getRequest } from "./api";

export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return;
    }
    getRequest("/system/authority/list").then(data => {
        if (data) {
            //  格式化Router
            let fmtRoutes = formatRoutes(data);
            // 添加到路由 两种方法
            //方法1 官方已弃用
            // router.addRoutes(fmtRoutes);

            //使用  matcher对象对外提供 addRoutes()方法,match()
            //参考http://t.csdn.cn/iPLR0
            //方法2
            for (let x of fmtRoutes) {
                router.matcher.addRoute(x)
                //router.addRoute(x)
            }
            //将数据存入vuex
            store.commit('initRoutes', fmtRoutes);

        }
    })
}

//  routes是从后端接收过来的data数据
export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(item => {
        let {
            path,
            component,
            name,
            children
        } = item;
        if (children && children instanceof Array) {
            // 递归
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            children: children,
            component(resolve) {
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                }
                else if (component.startsWith('System')) {
                    require(['../views/system/' + component + '.vue'], resolve);
                }
                else if (component.startsWith('Basic')) {
                    require(['../views/basic/' + component + '.vue'], resolve);
                }
            }
        }
        fmtRoutes.push(fmRouter)
    });
    return fmtRoutes;
}